package com.sino.operation.service.business;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sino.operation.Exception.exceptionRoot.SinoException;
import com.sino.operation.commons.ConstantValue;
import com.sino.operation.commons.commonEnum.StatusInfoEnum;
import com.sino.operation.config.persistence.MyPersistence;
import com.sino.operation.entity.*;
import com.sino.operation.entity.entityBasic.Register;
import com.sino.operation.mapper.*;
import com.sino.operation.peripheral.esc.request.cnaps2_000104.EscED0001_04Param;
import com.sino.operation.util.PersistenceUtil;
import com.sino.operation.util.ReflectExecuteUtil;
import com.sino.operation.util.RestTemplateUtils;
import com.sino.operation.util.UrlUtil;
import com.sino.operation.vo.current.TaskOtherCompleteParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Title: CommonNodeService
 * @Description:
 * @Author dengls
 * @date 2021/11/2 15:39
 */
@Service
@Slf4j
public class CommonNodeService {
    @Autowired(required = false)
    private SysAbMessageMapper sysAbMessageMapper;
    @Autowired(required = false)
    private BizTranslistMapper bizTranslistMapper;
    @Autowired(required = false)
    private BizExchangeInfoMapper bizExchangeInfoMapper;
    @Autowired(required = false)
    private BizInternalTransMapper bizInternalTransMapper;
    @Autowired(required = false)
    private BizMarginOpenAccountMapper bizMarginOpenAccountMapper;
    @Autowired(required = false)
    private BizDespositInfoMapper bizDespositInfoMapper;
    @Autowired
    private UrlUtil urlUtil;
    @Autowired
    private RestTemplateUtils restTemplateUtils;
    @Autowired
    private StringRedisTemplate redis;
    @Autowired
    private MyPersistence myPersistence;
    /**
     * 两录比对
     *
     * @param journalNo 流水号
     * @param transCode 交易码
     * @return
     */
    public String compareTwiceRecording(String journalNo, String transCode) {
        String compareState = "";//工作流参数
        Map<String, Object> comparResult = new HashMap<>();
        Map<String, Map> errorResult = new HashMap<>();
        Map<String, Map> correctResult = new HashMap<>();
        SysAbMessage sysAbMessage = sysAbMessageMapper.selectById(journalNo);
        BizTranslist bizTranslist = bizTranslistMapper.selectById(journalNo);
        Register info = null;
        String sliceFlage = bizTranslist.getSliceFlage();
        String messageTotal1 = sysAbMessage.getMessageTotal1();
        String messageTotal2 = sysAbMessage.getMessageTotal2();
        TaskOtherCompleteParam totalMsg1 = JSON.parseObject(messageTotal1, TaskOtherCompleteParam.class);
        TaskOtherCompleteParam totalMsg2 = JSON.parseObject(messageTotal2, TaskOtherCompleteParam.class);
        //获取整单录入表单内容
        Map<String, Map> Total1 = totalMsg1.getInfoInputs();
        Map<String, Map> Total2 = totalMsg2.getInfoInputs();
        Set<String> set = Total1.keySet();
        //比对两录不一致字段
        for (String key : set) {
            if (!Total1.get(key).equals(Total2.get(key))) {
                Map<String, String> error = new HashMap<>();
                error.put("Total1", Total1.get(key).get("value").toString());
                error.put("Total2", Total2.get(key).get("value").toString());
                error.put("CHE", Total1.get(key).get("CHE").toString());
                errorResult.put(key, error);

            } else {
                correctResult.put(key, Total1.get(key));
            }
        }
        comparResult.put("errorResult", errorResult);
        comparResult.put("correctResult", correctResult);
        log.info(comparResult.toString());

        if (errorResult.isEmpty() && StatusInfoEnum.SLICE_FLAGE.equals(sliceFlage)) {
            compareState = "2";//跨单比对
        } else if (!errorResult.isEmpty()) {
            compareState = "1";//修正岗,则更新实时报文和两录比对报文
            String jsonResult = JSON.toJSONString(comparResult);
            sysAbMessage.setCompareMessage(jsonResult);
            sysAbMessage.setMessage(jsonResult);
        } else {
            compareState = "0";//自动校验节点
            try {
                switch (transCode) {
                    case "710302":
                        info = bizExchangeInfoMapper.selectById(journalNo);
                        info = Exec_710302_Util.CollectionHandle(correctResult, (BizExchangeInfo) info);
                        bizExchangeInfoMapper.updateById((BizExchangeInfo) info);
                        break;
                    case "710304":
                        info = bizInternalTransMapper.selectById(journalNo);
                        info = Exec_710304_Util.CollectionHandle(correctResult, (BizInternalTrans) info);
                        bizInternalTransMapper.updateById((BizInternalTrans) info);
                        break;
                    case "710305":
                        info = bizMarginOpenAccountMapper.selectById(journalNo);
                        info = Exec_710305_Util.CollectionHandle(correctResult, (BizMarginOpenAccount) info);
                        bizMarginOpenAccountMapper.updateById((BizMarginOpenAccount) info);
                        break;
                    case "710306":
                        info = bizDespositInfoMapper.selectById(journalNo);
                        info = Exec_710306_Util.CollectionHandle(correctResult, (BizDespositInfo) info);
                        bizDespositInfoMapper.updateById((BizDespositInfo) info);
                        break;
                    default:
                        throw new SinoException(500, "交易码不存在");
                }
            } catch (SinoException e) {
                throw new SinoException(500, "两录比对异常，" + e.getMessage());
            }
        }
        sysAbMessageMapper.updateById(sysAbMessage);
        return compareState;
    }

    /**
     * 重复判断
     *
     * @param journalNo 流水号
     * @param transCode 交易码
     * @return
     */
    public String repeatJudge(String journalNo, String transCode) {
        String repeatFlag = "0";
        Register info = null;
        QueryWrapper<?> wrapper = null;
        List<?> list = null;
        switch (transCode) {
            case "710302":
                info = bizExchangeInfoMapper.selectById(journalNo);
                wrapper = Exec_710302_Util.repeatJudge((BizExchangeInfo) info);
                list = bizExchangeInfoMapper.selectList((Wrapper<BizExchangeInfo>) wrapper);
                break;
            case "710304":
                info = bizInternalTransMapper.selectById(journalNo);
                wrapper = Exec_710304_Util.repeatJudge((BizInternalTrans) info);
                list = bizInternalTransMapper.selectList((Wrapper<BizInternalTrans>) wrapper);
                break;
            case "710305":
                info = bizMarginOpenAccountMapper.selectById(journalNo);
                wrapper = Exec_710305_Util.repeatJudge((BizMarginOpenAccount) info);
                list = bizMarginOpenAccountMapper.selectList((Wrapper<BizMarginOpenAccount>) wrapper);
                break;
            case "710306":
                info = bizDespositInfoMapper.selectById(journalNo);
                wrapper = Exec_710306_Util.repeatJudge((BizDespositInfo) info);
                list = bizDespositInfoMapper.selectList((Wrapper<BizDespositInfo>) wrapper);
                break;
            default:
                throw new SinoException(500, "重复判断异常，交易码不存在");
        }
        if (list.size() > 0) {
            repeatFlag = "1";
        }
        return repeatFlag;
    }

    //授权规则
    public String AuthorizationRule(String businessKey,String transCode) {
        String authorization_flag = "0";
        if("710302".equals(transCode)){
            BizExchangeInfo bizExchangeInfo = bizExchangeInfoMapper.selectById(businessKey);
            String amount = bizExchangeInfo.getAmount();//获取金额
            if (amount != null && amount.isEmpty()) {
                return authorization_flag;
            }
            String s = amount.split("\\.")[0];
            if (Integer.parseInt(s) > 10000) {
                authorization_flag = "0";
            }
        }
        return authorization_flag;
    }

    //自动验印结果处理
    public String autoVerifyResult(String businessKey) {
        return "1";
    }

    //自动验印发送
    public String AutoVerifyStart(String businessKey) {
        return "";
    }

    //验印判断
    public String VerifyJudge(String businessKey) {
        return "1";
    }

    //记账服务
    public String ChargeHandle(String businessKey,String tranCode) throws Exception {
        String escToken = redis.opsForValue().get("escToken");
        if ("710302".equals(tranCode)) {
            BizExchangeInfo bizExchangeInfo = bizExchangeInfoMapper.selectById(businessKey);
            EscED0001_04Param escED0001_04Param = Exec_710302_Util.ed0001_04ParamHandle(bizExchangeInfo,escToken);
            String edUrl = urlUtil.getEDUrl(ConstantValue.EXCHANGE_SX_CNAPS2_PB0001_04);
            ResponseEntity<String> result = restTemplateUtils.post(edUrl, escED0001_04Param, String.class);
            String body = result.getBody();
        }
        BizTranslist bizTranslist = bizTranslistMapper.selectById(businessKey);
        PersistenceUtil persistence = ReflectExecuteUtil.execute("Exec_" + tranCode, "executeCharge", null, bizTranslist, null, null, null, null);
        List<Object> paramObject = persistence.getParamObject();
        myPersistence.save(paramObject);
        return "0";
    }
}
